package main

import (
	"fmt"
	"strings"
)

// We are building a word processor and we would like to implement a "reflow" functionality that also applies full justification to the text.
// Given an array containing lines of text and a new maximum width, re-flow the text to fit the new width. Each line should have the exact specified width. If any line is too short, insert '-' (as stand-ins for spaces) between words as equally as possible until it fits.
// Note: we are using '-' instead of spaces between words to make testing and visual verification of the results easier.

// lines = [ "The day began as still as the",
//           "night abruptly lighted with",
//           "brilliant flame" ]

// reflowAndJustify(lines, 24) ... "reflow lines and justify to length 24" =>
//         [ "The--day--began-as-still",
//           "as--the--night--abruptly",
//           "lighted--with--brilliant",
//           "flame" ] // <--- a single word on a line is not padded with spaces

func reflowAndJustify(lines []string, length int) []string {
	res := []string{}
	wordsComb := [][]string{}
	words := strings.Split(strings.Join(lines, " "), " ")
	for i := 0; i < len(words); {
		remainingLen := length
		minDashCount := 0
		j := i
		for j < len(words) && remainingLen-len(words[j])-minDashCount >= 0 {
			remainingLen = remainingLen - len(words[j]) - minDashCount
			minDashCount = 1
			j += 1
		}
		oneLine := []string{}
		for x := i; x < j; x++ {
			oneLine = append(oneLine, words[x])
		}
		i = j
		wordsComb = append(wordsComb, oneLine)
	}

	for _, words := range wordsComb {
		if len(words) == 1 {
			res = append(res, words[0])
			continue
		}
		dashCount := len(words) - 1
		dashArray := make([]string, dashCount)
		for i := range dashArray {
			dashArray[i] = "-"
		}
		// fmt.Println(dashArray)
		diff := length - len(strings.Join(words, "-"))
		for i := 0; diff != 0; {
			diff--
			dashArray[i] = dashArray[i] + "-"
			if i+1 == len(dashArray) {
				i = 0
			} else {
				i++
			}

		}
		oneLine := words[0]
		for i := 1; i < len(words); i++ {
			oneLine = oneLine + dashArray[i-1] + words[i]
		}
		res = append(res, oneLine)
	}
	return res
}

func main() {
	lines := []string{"The day began as still as the",
		"night abruptly lighted with",
		"brilliant flame"}
	// lines := []string{"It was the best of times it was the worst of time"}

	fmt.Println(reflowAndJustify(lines, 24))
}
